/* eslint-disable camelcase */
import React from 'react';
import _ from 'lodash';
import 'github-markdown-css';
import ReactMarkdown from 'react-markdown';
import fx from '../../utils/fx';
import moment from 'moment';

import commentsStyles from './Comments.less';

export const val = (v, decimal = 2) => (<em>{v === undefined ? 0 : fx.formatNumber(v, decimal)}</em>);
export const random_select = list => _random_select(list);

export const format_comments_array = (config) => {
	if (config != undefined && config.comment_text != undefined) {
		const comment_text = config.comment_text;
		for (const key in comment_text) {
			const value = comment_text[key];
			if (typeof value === 'object' && !isNaN(value.length)) {
				// array
				const select_value = random_select(value);
				config.comment_text[key] = [select_value];
			} else if (typeof value === 'object' && isNaN(value.length)) {
				// dict
				for (const dict_key in value) {
					const dict_value = value[dict_key];
					const select_dict_value = random_select(dict_value);
					config.comment_text[key][dict_key] = [select_dict_value];
				}
			}
		}
	}
	if (config != undefined && config.diagnosis_features != undefined) {
		const diagnosis_features = config.diagnosis_features;
		for (const key in diagnosis_features) {
			const value = diagnosis_features[key];
			const select_comments = random_select(value.comments);
			config.diagnosis_features[key].comments = [select_comments];
		}
	}
	return config;
};

const comments_key = 'comment_text';

const styleFormet = (content, styles) => {
	const styleMap = {
		green: 'green',
		red: 'red',
		strong: 'strong',
	}

	let className = '';
	_(styles).forEach(style => {
		className += `${styleMap[style]} `;
	})
	return `<span class="${className}">${content}\n</span>`;
	// return createElement('span', { class: className }, content);
}

function _format_number(v, decimal) {
		return v === undefined ? 0 : fx.formatNumber(v, decimal);
}

function format_number(v, decimal) {
	const value = _format_number(v, decimal)
	if (parseFloat(value) == 0) {
		// deal with -0.00
		return _format_number(0, decimal)
	} else {
		return value
	}
}

function auto_format_number(v, config, feature_name) {
	let decimal = 2
	if (config != undefined && feature_name != undefined && config['decimals'] != undefined && config['decimals'][feature_name] != undefined) {
		decimal = parseInt(config['decimals'][feature_name])
	}
	return format_number(v, decimal)
}

function _random_select(list) {
	if (list == undefined) {
		return undefined;
	}
	const random_index = Math.floor(Math.random() * list.length);
	const value = list[random_index];
	return value;
}

function generate_diagnosis_features(features, config, feature_ranks, diagnosis_features_key, comments_start_key, select_min_score) {
	if (config == undefined || features == undefined) {
		return '';
	}
	if (select_min_score == undefined) {
		select_min_score = false
	}

	const diagnosis_features = config[diagnosis_features_key];
	if (diagnosis_features == undefined) {
		return '';
	}

	let show_diagnosis_features = {}
	if (select_min_score) {
		let alert_feature_name;
		let alert_feature_score_name;
		for (const feature_name in diagnosis_features) {
			const feature_score_name = `score_${feature_name}`;
			const feature_score = features[feature_score_name];
			if (feature_score == undefined) {
				continue;
			}
			if (alert_feature_name == undefined || feature_score <= features[alert_feature_score_name]) {
				alert_feature_name = feature_name;
				alert_feature_score_name = feature_score_name;
				show_diagnosis_features = {}
				show_diagnosis_features[feature_name] = diagnosis_features[feature_name]
			}
		}
	} else {
		for (const feature_name in diagnosis_features) {
			const trigger = diagnosis_features[feature_name]['trigger']
			const feature_score_name = `score_${feature_name}`;
			const feature_score = features[feature_score_name];
			if (feature_score == undefined) {
				continue;
			}
			if (feature_score <= trigger) {
				show_diagnosis_features[feature_name] = diagnosis_features[feature_name]
			}
		}
	}

	let text = ''
	for (const feature_name in show_diagnosis_features) {

		let single_text = ''
		single_text = _random_select(diagnosis_features[feature_name].comments);
		single_text = single_text.replace(new RegExp('\\_\\$\\_', 'g'), auto_format_number(features[feature_name], config, feature_name));
		text += `${single_text}\n\n`;

	}

	if (text != undefined && text != '' && comments_start_key != undefined && comments_start_key != '' && config[comments_key] != undefined && config[comments_key][comments_start_key] != undefined) {
		const comments_start = _random_select(config[comments_key][comments_start_key]);
		text = `${comments_start}\n\n${text}`;
	}

	return text;
}

function pivots(features, config, feature_ranks, features_key, feature_pivots_key, comments_start_key) {
	if (config == undefined || features == undefined) {
		return '';
	}

	const feature_list = config[features_key];
	const feature_pivots = config[feature_pivots_key];
	const comments = config[comments_key];

	if (feature_list == undefined || feature_pivots == undefined || comments == undefined) {
		return '';
	}

	let text = '';
	for (let index = 0; index < feature_list.length; index++) {
		const feature_name = feature_list[index];
		const feature_value = features[feature_name];
		const feature_stages = feature_pivots[feature_name];
		const feature_comments = comments[feature_name];
		if (feature_value == undefined || feature_stages == undefined || feature_comments == undefined) {
			continue;
		}

		let stage_index = 0;
		for (let index = 0; index < feature_stages.length; index++) {
			const value = feature_stages[index];
			if (feature_value >= value) {
				stage_index++;
			}
		}

		const stage_comments_key = `${feature_name}_${stage_index}`;
		const stage_comments = feature_comments[stage_comments_key];
		if (stage_comments == undefined) {
			continue;
		}
		let stage_comments_text = _random_select(stage_comments);
		stage_comments_text = stage_comments_text.replace(new RegExp('\\_\\$\\_', 'g'), auto_format_number(feature_value, config, feature_name));
		if (feature_ranks != undefined) {
			const filter_feature_ranks = feature_ranks.filter(rank => rank.featureName == feature_name);
			if (filter_feature_ranks && filter_feature_ranks.length != 0) {
				const feature_rank = filter_feature_ranks[0];
				const percent = format_number((feature_rank.rank * 100) / feature_rank.total, 2);
				stage_comments_text = stage_comments_text.replace(new RegExp('\\_\\#\\_', 'g'), percent);
			}
		}

		text += `${stage_comments_text}\n\n`;
	}

	if (text != undefined && text != '' && comments_start_key != undefined && comments_start_key != '' && config[comments_key] != undefined && config[comments_key][comments_start_key] != undefined) {
		const comments_start = _random_select(config[comments_key][comments_start_key]);
		text = `${comments_start}\n\n${text}`;
	}

	return text;
}

function generate_positions(features, config, special_tradings, special_type, highlights_key) {
	if (config == undefined || features == undefined || special_tradings == undefined || special_type == undefined || highlights_key == undefined) {
		return '';
	}

	const filter_special_tradings = special_tradings.filter((special_trading, index, array) => special_trading.specialType == special_type);
	if (filter_special_tradings == undefined || filter_special_tradings.length == 0) {
		return '';
	}
	const special_trading = filter_special_tradings[0];
	const filter_closed_positions = special_trading.closeOrder.closedPositionList.filter(cp => cp.openOrderId == special_trading.openOrderId && cp.closeOrderId == special_trading.closeOrderId);
	if (filter_closed_positions == undefined || filter_closed_positions.length == 0) {
		return '';
	}
	const closed_position = filter_closed_positions[0];
	const open_time =  moment(new Date(closed_position.openTime)).format('YYYY-MM-DD HH:mm');
	const symbol = closed_position.symbol;
	const realized_net = (closed_position.sellPrice - closed_position.buyPrice) * closed_position.quantity - closed_position.fee;

	let text = _random_select(config.comment_text.order_highlights[highlights_key]);
	text = text.replace('_1_', open_time);
	text = text.replace('_2_', symbol);
	text = text.replace('_3_', auto_format_number(realized_net, config, highlights_key));

	return text;
}

function generate_special_tradings(features, config, special_tradings) {
	const max_profit_text = generate_positions(features, config, special_tradings, 'max_profit', 'best_order');
	const max_loss_text = generate_positions(features, config, special_tradings, 'max_loss', 'worst_order');

	let text = ''
	if (max_profit_text != undefined && max_profit_text != '') {
		text += `${max_profit_text}\n\n`;
	}
	if (max_loss_text != undefined && max_loss_text != '') {
		text += `${max_loss_text}\n\n`;
	}
	if (text != undefined && text != '' && config[comments_key] != undefined && config[comments_key]['trading_start'] != undefined) {
		const trading_start = _random_select(config[comments_key]['trading_start']);
		text = `${trading_start}\n\n${text}`;
	}

	return text
}

function generate_pivots(features, config, feature_ranks) {
	if (config == undefined || features == undefined) {
		return '';
	}

	let sorted_keys = []
	for (var key in config) {
		if (key.startsWith('sorted_')) {
				sorted_keys.push(key)
		}
	}

	let text = ''
	for (let index = 0; index < sorted_keys.length; index++) {
		const sorted_key = sorted_keys[index];
		const keyword = sorted_key.replace('sorted_', '')
		let pivots_key = keyword + '_pivots'
		let comments_start_key = keyword + '_start'
		if (keyword.endsWith('s')) {
				const keyword_singular = keyword.substring(0, keyword.length-1)
				pivots_key = config[pivots_key] != undefined? pivots_key: (keyword_singular + '_pivots')
				if (config[comments_key] != undefined) {
						comments_start_key = config[comments_key][comments_start_key] != undefined? comments_start_key: (keyword_singular + '_start')
				}
		}

		const keyword_text = pivots(features, config, feature_ranks, sorted_key, pivots_key, comments_start_key);
		if (keyword_text != undefined && keyword_text != '') {
			text += `${keyword_text}\n\n`;
		}
	}

	return text;
}

export default function Comments({ features, config, special_tradings, feature_ranks }) {
	const general_start = config === undefined ? '' : _random_select(config.comment_text.general_start);
	// const dimension_text = pivots(features, config, feature_ranks, 'sorted_dimensions', 'dimension_pivots', undefined);
	// const feature_text = pivots(features, config, feature_ranks, 'sorted_features', 'feature_pivots', 'feature_start');
	const pivots_text = generate_pivots(features, config, feature_ranks);
	const diagnosis_features_text = generate_diagnosis_features(features, config, feature_ranks, 'diagnosis_features', 'alert_start');
	const tradings_text = generate_special_tradings(features, config, special_tradings)
	return (
		<div className="analysis-comments markdown-body" style={{ fontSize: 12, lineHeight: 1 }}>
			<ReactMarkdown source={general_start} />
			<ReactMarkdown source={pivots_text} />
			<br />
			<ReactMarkdown source={diagnosis_features_text} />
			<br />
			<ReactMarkdown source={tradings_text} />
			<br />
		</div>
	);
}
